package me.ivps.android.servicedemo.service;

import java.util.Date;

import me.ivps.android.servicedemo.MainApp;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class AnotherService extends Service {
    
    private static final String TAG = "AnotherService";
    
    public static final String Action_Start = "me.ivps.android.anotherservice.start";
    
    public static final String Action_Stop = "me.ivps.android.anotherservice.stop";
    
    private MainApp mApp;
    
    private UpdateThread mThread;
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
        mApp = (MainApp) getApplication();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        mApp = (MainApp) getApplication();
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind");
        return null;
    }
    
    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind");
        return super.onUnbind(intent);
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        if (intent != null) {
            if (Action_Start.equals(intent.getAction())) {
                startUpdate();
            }
            else if (Action_Stop.equals(intent.getAction())) {
                stopUpdate();
            }
            
            return START_NOT_STICKY;
        }
        return super.onStartCommand(intent, flags, startId);
    }
    
    public void startUpdate() {
        Log.d(TAG, "onStartUpdate");
        if (mThread != null) {
            mThread.interrupt();
            mThread = null;
        }
        mThread = new UpdateThread();
        mThread.start();
    }
    
    public void stopUpdate() {
        Log.d(TAG, "onStopUpdate");
        if (mThread != null) {
            mThread.interrupt();
            mThread = null;
        }
    }
    
    class UpdateThread extends Thread {
        
        @Override
        public void run() {
            Log.d(TAG, "Start Update");
            while (!interrupted()) {
                Log.d(TAG, "Generate New String");
                mApp.addText(new Date().toString());
                try {
                    Thread.sleep(2000L);
                }
                catch (InterruptedException e) {
                    Log.e(TAG, "Thread Error", e);
                    interrupt();
                }
            }
            Log.d(TAG, "Stop Update");
        }
    }
    
}
